'''
A script that shows how to run many emulated Ping-Pong applications
under TwistedSim using process-based emulation.

@author: Hatem Oraby
'''
import twistedSim.simManager as simManager 
from twistedSim.moduleHandler import twistedH

numOfPeers = 30
pingLimit = 200

def main():
    parseSysArgs()
        
    trackerIP = '176.10.0.1'
    #Tracker
    trackerMachine = simManager.Machine()
    trackerInterface = simManager.IpInterface(trackerIP, trackerMachine)
    trackerModule = simManager.Module('tracker', handler = twistedH())
    simManager.SimManager.addModule(trackerModule, trackerMachine)
    
    #Peers
    firstParts = "42.30." #42.30.125.0'
    secondPart = 125
    thirdPart = 0
    time = 0
    for i in range(numOfPeers):
        peerMachine = simManager.Machine()
        #Construct IP
        if thirdPart == 255:
            thirdPart = 0
            secondPart += 1
        ip = firstParts + str(secondPart) + "." + str(thirdPart) 
        thirdPart += 1
        peerInterface = simManager.IpInterface(ip, peerMachine)
        peerSysArgs = trackerIP + ":2000 " + str(pingLimit)
        peerModule = simManager.Module('peer', twistedH(), 
                                         startTime = time + i,
                                         sysArgs = peerSysArgs,
                                         nickName = "peer" + str(i))
        simManager.SimManager.addModule(peerModule, peerMachine)
    
    trackTime()
    simManager.SimManager.run()

def trackTime():
    import time
    from twistedSim.overrideManager import OverrideManager
    realAscTime = OverrideManager.getEntity("time.asctime")
    realTime = OverrideManager.getEntity("time.time")
    startTime = time.time()
    def concludeTime():
        print "PingPong: " 
        print "Peers: ", numOfPeers, "\t Limit: ",pingLimit
        print "Time now: " + time.asctime()
        print "Time since i started: " + str(time.time() - startTime)
        print "Real TIme: " + realAscTime()
        print "Real time since i started: " + str(realTime() - startTime)
        print "Simulated - Real = " + str(time.time() - realTime())
    
    simManager.SimManager.addPostRun(concludeTime)


def parseSysArgs():
    global pingLimit, numOfPeers
    import sys
    if len(sys.argv) ==  3:
        numOfPeers = int(sys.argv[1])
        pingLimit = int(sys.argv[2])

if __name__ == '__main__':
    main()